iT邦幫忙

2023 iThome 鐵人賽

DAY 15
0
自我挑戰組

設計模式系列 第 15

Day15 - 責任鏈模式(Chain of responsibility pattern)

  • 分享至 

  • xImage
  •  

介紹
責任鏈模式為將請求發送至一條由多個物件串成的鏈,請求會逐一被鏈上的物件處理,直到該請求被完成。

C++範例

#include <iostream>

// 抽象處理物件: 可被處理不同需求的物件實作
class Handler
{
public:
    Handler() : m_next(nullptr)
    {
    }

    virtual ~Handler() {}

    virtual void Request(int value) = 0;

    void SetNextHandler(Handler *pHandler)
    {
        m_next = pHandler;
    }

protected:
    Handler *m_next;
};

// 具體處理物件: 處理傳入且符合處理條件的請求
class SpecialHandler : public Handler
{
public:
    SpecialHandler(int limit, int id) : m_limit(limit), m_handlerID(id)
    {
    }

    ~SpecialHandler() {}

    // 只處理符合條件的請件,反之則將請求往鏈上的下個物件傳送
    void Request(int value)
    {
        if (value < m_limit)
        {
            std::cout << "Handler " << m_handlerID << " handled the request with value " << value << std::endl;
        }
        else if (m_next != NULL)
        {
            std::cout << "Handler " << m_handlerID << " can't handle this request. Request sends to the next element" << std::endl;
            m_next->Request(value);
        }
        else
        {
            std::cout << "The request reaches to the last element in chain and no one can handle it" << std::endl;
        }
    }

private:
    int m_limit;
    int m_handlerID;
};

int main()
{
    // 創建處理物件
    Handler *h1 = new SpecialHandler(10, 1);
    Handler *h2 = new SpecialHandler(20, 2);
    Handler *h3 = new SpecialHandler(30, 3);

    // 將物件串起來
    h1->SetNextHandler(h2);
    h2->SetNextHandler(h3);

    std::cout << "A request with value 18 sends to the chain" << std::endl;
    // 將請求從鏈頭傳入
    h1->Request(18);

    std::cout << "A request with value 40 sends to the chain" << std::endl;
    // 將請求從鏈頭傳入
    h1->Request(40);

    delete h1;
    delete h2;
    delete h3;

    return 0;
}

Output:

A request with value 18 sends to the chain
Handler 1 can't handle this request. Request sends to the next element
Handler 2 handled the request with value 18
A request with value 40 sends to the chain
Handler 1 can't handle this request. Request sends to the next element
Handler 2 can't handle this request. Request sends to the next element
The request reaches to the last element in chain and no one can handle it

上一篇
Day14 - 代理模式(Proxy pattern)
下一篇
Day16 - 策略模式(Strategy pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言